/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.dept.repository;

import com.lap.auth.adapter.driving.persistence.dept.DeptConverter;
import com.lap.auth.adapter.driving.persistence.dept.mapper.DeptMapper;
import com.lap.auth.adapter.driving.persistence.dept.po.DeptPo;
import com.lap.auth.domain.dept.Dept;
import com.lap.auth.domain.dept.repository.DeptRepository;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class DeptRepositoryImpl implements DeptRepository {

  private final DeptConverter converter;
  private final DeptMapper deptMapper;

  @Override
  public Integer save(Dept dept) {
    DeptPo deptPo = converter.toPo(dept);
    if (dept.isNew()) {
      deptMapper.insert(deptPo);
      return deptPo.getId();
    }
    return deptMapper.updateById(deptPo);
  }

  @Override
  public int deleteById(Integer id) {
    return deptMapper.deleteById(id);
  }

  @Override
  public List<Dept> findAll() {
    List<DeptPo> all = deptMapper.selectAll();
    return converter.toDomains(all);
  }

  @Override
  public List<Dept> findByPid(Integer pid) {
    List<DeptPo> children = deptMapper.selectByPid(pid);
    return converter.toDomains(children);
  }

  @Override
  public List<Dept> findByIds(List<Integer> ids) {
    List<DeptPo> list = deptMapper.selectByIds(ids);
    return converter.toDomains(list);
  }

  @Override
  public Optional<Dept> findById(Integer id) {
    var deptDO = deptMapper.selectById(id);
    return Optional.ofNullable(converter.toDomain(deptDO));
  }
}
